package com.heliang.ui.info;

import java.util.List;

import net.tsz.afinal.FinalBitmap;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.text.TextPaint;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.appxiehui2.R;
import com.heliang.common.ImageDispose;
import com.heliang.dataaccess.bean.AdvBean;
import com.heliang.dataaccess.bean.AdvFooterBean;
import com.heliang.dataaccess.bean.InfoBean;
import com.heliang.dataaccess.bean.MailListBean;
import com.heliang.util.AppUtil;
import com.heliang.util.Constants;
import com.heliang.util.ImageLoaderAddLoadingUtil;
import com.hl.component.LoadindImageView;
import com.hl.component.LoadingView;
import com.hl.component.PageControl;
import com.hl.component.SwipeView;
import com.hl.component.SwipeView.OnPageChangedListener;

public class IndexAdapter2 extends BaseAdapter {

    private List<AdvBean> advTopBeans;
    private List<AdvFooterBean> advFooterBeans;
    private List<InfoBean> infoItemBeans;
    private List<InfoBean> infoBeans;
    private List<MailListBean> mailListBeans;
    private Activity activity;
    private int currentItem = 0;
    private TextView advTitle;
    private List<View> dots;
    private ViewPager viewPager;

    private RelativeLayout relativeLayout, footRelativeLayout;
    private SwipeView swipeView;
    private PageControl pageControl;
    private Bitmap bitmap;

    public IndexAdapter2(Activity activity, List<AdvBean> advTopBeans, List<AdvFooterBean> advFooterBeans, List<InfoBean> infoItemBeans,
        List<MailListBean> mailListBeans, List<InfoBean> infoBeans) {
        this.advTopBeans = advTopBeans;
        this.advFooterBeans = advFooterBeans;
        this.infoItemBeans = infoItemBeans;
        this.mailListBeans = mailListBeans;
        this.activity = activity;
        this.infoBeans = infoBeans;

    }

    @Override
    public int getCount() {
        int count = 7;
        return count;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        LayoutInflater inflater = activity.getLayoutInflater();
        if (position == 0) {
            rowView = null;
            rowView = inflater.inflate(R.layout.search_bar, null);
            ImageView searchImage = (ImageView) rowView.findViewById(R.id.serch);
            searchImage.setOnClickListener(searcheOnclick);
        } else if (position == 1 && advTopBeans.size() > 0) {
            rowView = null;
            if (relativeLayout != null) {
                rowView = relativeLayout;
                return rowView;
            }

            rowView = inflater.inflate(R.layout.banner, null);
            relativeLayout = (RelativeLayout) rowView;

            swipeView = (SwipeView) rowView.findViewById(R.id.banner_swipe_view);
            pageControl = (PageControl) rowView.findViewById(R.id.banner_page_control);

            init();
            swipeView.setPageControl(pageControl);
        } else if (position == 5) {
            rowView = null;
            rowView = inflater.inflate(R.layout.recomand_store, null);
            if (mailListBeans != null && mailListBeans.size() > 0) {
                Gallery aliveMember = (Gallery) rowView.findViewById(R.id.alive_member_people);
                AliveMemberAdapter aliveAdapter = new AliveMemberAdapter(activity, mailListBeans);
                aliveMember.setAdapter(aliveAdapter);
            } else {
                LinearLayout linerLayout = (LinearLayout) rowView.findViewById(R.id.alive_member_layout);
                linerLayout.setVisibility(View.GONE);
            }
        } else if (position == 6) {
            rowView = null;
            rowView = inflater.inflate(R.layout.index_footer, null);
        } else {
            rowView = null;
            rowView = inflater.inflate(R.layout.info_list_item, null);
            if (infoBeans != null && infoBeans.size() > 0) {
                rowView.setBackgroundResource(R.drawable.list_item_seletor);
                FrameLayout ll = (FrameLayout) rowView.findViewById(R.id.list_item_head_layout);

                TextView titleTv = (TextView) rowView.findViewById(R.id.recommend_list_item_title_textview);
                TextPaint tp = titleTv.getPaint();
                tp.setFakeBoldText(true);

                TextView descTv = (TextView) rowView.findViewById(R.id.recommend_list_item_desc_textview);
                ImageView pushIconIv = (ImageView) rowView.findViewById(R.id.push_icon);
                ImageView headIv = (ImageView) rowView.findViewById(R.id.list_item_head_image);
                headIv.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.info_default_icon));
                // ImageView clipsIv =
                // (ImageView)rowView.findViewById(R.id.clips_icon);

                descTv.setLines(2);

                InfoBean infoBean = infoItemBeans.get(position);

                pushIconIv.setVisibility(View.VISIBLE);
                if (!infoBean.isRecommend()) {
                    pushIconIv.setVisibility(View.GONE);
                }
                if (infoBean.isFirstNews()) {// 头条
                    pushIconIv.setVisibility(View.VISIBLE);
                    pushIconIv.setImageResource(R.drawable.is_hot);
                }

                if (infoBean.isRead()) {
                    titleTv.setTextColor(activity.getResources().getColor(R.color.info_list_item_has_read_title));
                    descTv.setTextColor(activity.getResources().getColor(R.color.info_list_item_has_read_desc));
                }

                if (infoBean.getPic2Url() != null && !infoBean.getPic2Url().equals("")) {

                    ll.setVisibility(View.VISIBLE);
                    headIv.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.defaulte_head_icon));

                    FinalBitmap finalBitMap = FinalBitmap.create(activity);
                    finalBitMap.display(headIv, infoBean.getPic2Url());

                    // ImageLoaderUtil.instance.setImageDrawable(infoBean.getPic2Path(),
                    // infoBean.getPic2Url(), headIv, true);
                    rowView.setTag(R.id.list_item_head_image, headIv);
                } else {
                    // ll.setVisibility(View.GONE);
                }

                int titleWordCount = AppUtil.getWordCount((int) ((Constants.SCREEN_WIDTH - headIv.getDrawable().getIntrinsicWidth() - 62)),
                    titleTv.getTextSize()) - 2;// -2是去除省略号占用的长度
                int descWordCount = AppUtil.getWordCount((int) ((Constants.SCREEN_WIDTH - headIv.getDrawable().getIntrinsicWidth() - 62) * 2),
                    descTv.getTextSize()) - 2;

                String titleStr = infoBean.getTitle();
                String descStr = infoBean.getContent();

                if (infoBean.getTitle().length() > titleWordCount) {
                    titleStr = infoBean.getTitle().substring(0, titleWordCount) + "...";
                }

                if (infoBean.getContent().length() > descWordCount) {
                    descStr = infoBean.getContent().substring(0, descWordCount) + "...";
                }
                titleTv.setText(titleStr);
                descTv.setText(descStr);
                rowView.setTag(infoBean);
            }
        }

        return rowView;
    }

    /**
     * 收索框点击
     */
    private OnClickListener searcheOnclick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(activity, "search", Toast.LENGTH_SHORT).show();
        }

    };

    /**
     * 初始化图片
     * @param iv
     */
    private LoadingView imageViewSetImage(LoadingView liv) {
        LoadingView livBack = liv;
        try {
            AdvBean advBean = (AdvBean) livBack.getChildAt(0).getTag();
            livBack = ImageLoaderAddLoadingUtil.instance.setImageDrawableZoom(advBean.getImgPath(), advBean.getImgUrl(), liv);
            if (livBack != liv && livBack.getParent() != null) {
                ((FrameLayout) livBack.getParent()).removeView(livBack);
            }
            livBack.getChildAt(0).setOnClickListener(bannerOnClickListener);
        } catch (Exception e) {
            // TODO: handle exception
            Log.e(Constants.TAG, e.getMessage());
        }
        return livBack;
    }

    // 界面切换
    private class BannerSwipeImageLoader implements OnPageChangedListener {

        public void onPageChanged(int oldPage, int newPage) {

            if (newPage > oldPage) {// going forwards
                if (newPage != (swipeView.getPageCount() - 1)) {// if at the
                                                                // end, don't
                                                                // load one page
                    // after the end
                    LoadingView v = new LoadindImageView(activity, bitmap, false);
                    AdvBean advBean = (AdvBean) advTopBeans.get(newPage + 1);
                    v.getChildAt(0).setTag(advBean);
                    v.getChildAt(0).setOnClickListener(bannerOnClickListener);
                    v = imageViewSetImage(v);
                    LayoutParams lpForText = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
                    lpForText.gravity = Gravity.BOTTOM;
                    FrameLayout frameLayout = new FrameLayout(activity);

                    TextView tv = createDescTextView(advTopBeans.get(newPage + 1).getDec());

                    frameLayout.addView(v);
                    frameLayout.addView(tv, lpForText);

                    ((FrameLayout) swipeView.getChildContainer().getChildAt(newPage + 1)).addView(frameLayout);
                }
                if (oldPage != 0)// if at the beginning, don't destroy one
                                 // before the beginning
                {
                    ((FrameLayout) swipeView.getChildContainer().getChildAt(oldPage - 1)).removeAllViews();
                }

            } else {// going backwards
                if (newPage != 0) {// if at the beginning, don't load one before
                                   // the beginning
                    LoadingView v = new LoadindImageView(activity, bitmap, false);
                    AdvBean advBean = (AdvBean) advTopBeans.get(newPage - 1);
                    v.getChildAt(0).setTag(advBean);
                    v.getChildAt(0).setOnClickListener(bannerOnClickListener);
                    v = imageViewSetImage(v);

                    LayoutParams lpForText = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
                    lpForText.gravity = Gravity.BOTTOM;
                    FrameLayout frameLayout = new FrameLayout(activity);

                    TextView tv = createDescTextView(advTopBeans.get(newPage - 1).getDec());

                    frameLayout.addView(v);
                    frameLayout.addView(tv, lpForText);

                    ((FrameLayout) swipeView.getChildContainer().getChildAt(newPage - 1)).addView(frameLayout);
                }
                if (oldPage != (swipeView.getPageCount() - 1))// if at the end,
                                                              // don't destroy
                                                              // one page after
                                                              // the end
                {
                    ((FrameLayout) swipeView.getChildContainer().getChildAt(oldPage + 1)).removeAllViews();
                }
            }

        }

    };

    // 单击缩略图响应
    private OnClickListener bannerOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent;
            switch (v.getId()) {
            // case R.id.search_relativelayout:
            // intent = new Intent(activity,SearchIndexActivity.class);
            // intent.putExtra("searchtype", 0);
            // activity.startActivity(intent);
            // AnimCommon.set(R.anim.push_right_in,R.anim.push_left_out);
            // break;
            // case R.id.newest_member:
            // intent = new Intent(activity,NewestMemberActivity.class);
            // activity.startActivity(intent);
            // AnimCommon.set(R.anim.push_right_in,R.anim.push_left_out);
            // break;
            // case R.id.newest_info:
            // intent = new Intent(activity,NewestInfoActivity.class);
            // activity.startActivity(intent);
            // AnimCommon.set(R.anim.push_right_in,R.anim.push_left_out);
            // break;
            // case CLOSE_IMAGEVIEW_ID:
            // footFrameLayout.removeAllViews();
            // break;
            // default:
            // try {
            // AdvBean advBean = (AdvBean)v.getTag();
            // intent = new Intent(activity,BrowserActivity.class);
            // intent.putExtra("url", advBean.getUrl());
            //
            // activity.startActivity(intent);
            // AnimCommon.set(R.anim.push_right_in,R.anim.push_left_out);
            // //调用PV统计接口
            // takePv();
            // } catch (Exception e) {
            // // TODO: handle exception
            // FileLog.log("InfoListAdapter.bannerOnClickListener " +
            // e.getMessage());
            // }
            // break;
            }
        }
    };

    /**
     * @return
     */
    private TextView createDescTextView(String text) {
        TextView textView = new TextView(this.activity);
        textView.setBackgroundResource(R.drawable.banner_desc);
        textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        textView.setText(text);
        textView.setPadding(5, 0, 0, 0);
        textView.setTextColor(this.activity.getResources().getColor(R.color.white));
        textView.setTextSize(20);

        return textView;
    }

    private void init() {

        bitmap = ImageDispose.drawableToBitmap(this.activity.getResources().getDrawable(R.drawable.banner_default));
        bitmap = ImageDispose.zoomBitmap(bitmap, Constants.SCREEN_WIDTH, Constants.SCREEN_WIDTH * bitmap.getHeight() / bitmap.getWidth());

        for (int i = 0; i < advTopBeans.size(); i++) {
            swipeView.addView(new FrameLayout(this.activity));
        }

        LoadingView v0 = new LoadindImageView(this.activity, bitmap, false);
        v0.getChildAt(0).setTag(this.advTopBeans.get(0));
        v0.getChildAt(0).setOnClickListener(bannerOnClickListener);
        v0 = imageViewSetImage(v0);

        LayoutParams lpForText = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        lpForText.gravity = Gravity.BOTTOM;
        FrameLayout frameLayout = new FrameLayout(this.activity);

        TextView tv0 = createDescTextView(this.advTopBeans.get(0).getDec());

        frameLayout.addView(v0);
        frameLayout.addView(tv0, lpForText);

        ((FrameLayout) swipeView.getChildContainer().getChildAt(0)).addView(frameLayout);

        if (this.advTopBeans.size() > 1) {
            LoadingView v1 = new LoadindImageView(this.activity, bitmap, false);
            v1.getChildAt(0).setTag(this.advTopBeans.get(1));
            v1.getChildAt(0).setOnClickListener(bannerOnClickListener);
            v1 = imageViewSetImage(v1);

            FrameLayout frameLayout1 = new FrameLayout(this.activity);

            TextView tv1 = createDescTextView(this.advTopBeans.get(1).getDec());

            frameLayout1.addView(v1);
            frameLayout1.addView(tv1, lpForText);
            ((FrameLayout) swipeView.getChildContainer().getChildAt(1)).addView(frameLayout1);
        }

        BannerSwipeImageLoader mSwipeImageLoader = new BannerSwipeImageLoader();
        swipeView.setOnPageChangedListener(mSwipeImageLoader);
    }

}
